package com.hongyi.modelcontest.modular.wechat.service;

import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import com.alibaba.fastjson.JSONObject;
import com.hongyi.modelcontest.core.util.HttpClientUtil;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class WxTokenService {

    private static final Integer JSP_TIK_SUCCESS = 0;

    @Cacheable(value = "WE_CHAT")
    public String getBaseAccessToken(String appId, String secret) {
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId +
                "&secret=" + secret;
        String s = HttpClientUtil.httpGetRequest(url);
        JSONObject jsonObject = JSONObject.parseObject(s);
        if (jsonObject.getString("errcode") != null) {
            throw new ServiceException(500, jsonObject.getString("errmsg"));
        }
        return jsonObject.getString("access_token");
    }

    @Cacheable(value = "WE_CHAT")
    public String getJsApiTicKetAccessToken(String baseToken) {
        String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + baseToken +
                "&type=jsapi";
        String s = HttpClientUtil.httpGetRequest(url);
        JSONObject jsonObject = JSONObject.parseObject(s);
        if (!JSP_TIK_SUCCESS.equals(jsonObject.getInteger("errcode"))) {
            throw new ServiceException(500, jsonObject.getString("errmsg"));
        }
        return jsonObject.getString("ticket");
    }

}
